package com.xiaouyudeguang.common.executor;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.xiaouyudeguang.common.entity.CodeBody;
import com.xiaouyudeguang.common.utils.JsonObject;
import com.xiaouyudeguang.common.utils.PingYinUtils;
import com.xiaouyudeguang.common.utils.StringUtils;
import com.xiaouyudeguang.common.utils.TypeEnums;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class ExcelExecutor {

    public static void execute(String path) throws IOException {
        execute(new File(path));
    }

    public static void execute(File file) throws IOException {
        execute(Files.newInputStream(file.toPath()));
    }

    public static void execute(InputStream inputStream) {
        EasyExcel.read(inputStream, CodeBody.class, new ReadListener<CodeBody>() {
            @Override
            public void invoke(CodeBody data, AnalysisContext context) {
                try {
                    data.setGroup(PingYinUtils.transform(data.getGroup()));
                    if (StringUtils.isBlank(data.getBasePackage())) {
                        data.setBasePackage("com." + data.getGroup() + ".platform");
                    }
                    if (StringUtils.isBlank(data.getComment())) {
                        data.setComment(data.getTableName() + "表");
                    }
                    data.setModule(PingYinUtils.transform(data.getModule()));
                    data.setTableName(data.getModule() + "_" + PingYinUtils.transform(data.getTableName()));
                    data.setColumns(transform(data.getColumn()));
                    data.setToPinyin(true);
                    data.execute();
                } catch (Exception e) {
                    log.info(e.getMessage(), e);
                }
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext context) {
            }
        }).sheet().doRead();
    }

    public static Map<String, String> transform(String columns) throws Exception {
        Map<String, String> columnMap = new HashMap<>();
        if (StringUtils.isBlank(columns)) {
            return columnMap;
        }
        if (columns.startsWith("{") && columns.endsWith("}")) {
            Map<String, String> map = JsonObject.toMap(columns);
            map.forEach((key, value) -> {
                columnMap.put(key, TypeEnums.getType(value));
            });
            return columnMap;
        }
        columns = columns.replace("\t", "").replace("\n", "");
        String[] columnArray = columns.split(" ");
        if (columns.contains(",")) {
            columnArray = columns.split(",");
        } else if (columns.contains("，")) {
            columnArray = columns.split("，");
        } else if (columns.contains("；")) {
            columnArray = columns.split("；");
        } else if (columns.contains(";")) {
            columnArray = columns.split(";");
        }
        for (String column : columnArray) {
            if (column.contains("(") && column.contains(")")) {
                String comment = column.substring(0, column.indexOf("("));
                String type = TypeEnums.getType(column.substring(column.indexOf("(") + 1, column.indexOf(")")));
                columnMap.put(comment, type);
            } else if (column.contains("（") && column.contains("）")) {
                String comment = column.substring(0, column.indexOf("（"));
                String type = TypeEnums.getType(column.substring(column.indexOf("（") + 1, column.indexOf("）")));
                columnMap.put(comment, type);
            } else {
                columnMap.put(column, "varchar(50)");
            }
        }
        return columnMap;
    }
}
